<!--
  * 库位列表
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <a-col :span="4">
          <a-form-item label="库位编码" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.code" placeholder="库位编码" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="是否闲置" class="smart-margin-bottom0">
            <a-select v-model:value="queryForm.is_idle" placeholder="是否闲置" allowClear>
              <a-select-option :value="1">是</a-select-option>
              <a-select-option :value="2">否</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <!-- <a-button @click="addLocation" type="primary" v-privilege="'warehouse:position:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新增库位
        </a-button>
        <a-button @click="showImportModal" type="primary" v-privilege="'warehouse:position:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          批量新增
        </a-button>

        <a-button @click="confirmBatchDelete()" danger :disabled="selectedRowKeyList.length === 0" v-privilege="'warehouse:position:del'">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>

        <a-button @click="printCode()" :disabled="selectedRowKeyList.length === 0">
          <template #icon>
            <BarcodeOutlined />
          </template>
          批量生成库位码
        </a-button>

        <a-button @click="onExport" type="primary" v-privilege="'warehouse:position:export'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button> -->
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'is_idle'">
            <a-tag :bordered="false" color="blue" v-if="text === 1">闲置</a-tag>
            <a-tag :bordered="false" color="orange" v-else>占用</a-tag>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <!-- <a-button @click="updateLocation(record)" type="link" v-privilege="'warehouse:position:edit'">编辑</a-button>
              <a-button @click="deleteData(record.id, record.code)" danger type="link" v-privilege="'warehouse:position:del'">删除</a-button> -->
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
  </a-card>
  <!-- 批量新增 -->
  <ImportModal ref="importModalRef" @download-excel="exportTemplate" :import-excel="locationApi.import" @reloadList="queryData" />
  <!-- 库位码打印 -->
  <BarcodeDetail ref="barcodeDetailRef" />
</template>
<script setup lang="ts">
import BarcodeDetail from './barcode-detail.vue'
import _ from 'lodash'
import { message, Modal } from 'ant-design-vue'
import { locationApi } from '@/api/business/storage/warehouse-api'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import { errorSentry } from '@/lib/error-sentry'
import TableOperator from '@/components/support/table-operator/index.vue'
import ImportModal from '@/components/support/import-modal/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useQuery } from '@/hooks/web/use-query-hook'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import eventEmitter from '@/lib/event-emitter'
import customEventName from '@/views/business/storage/warehouse/warehouse/warehouse-event-name'
const appConfigStore = useAppConfigStore()

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '库位编码',
    dataIndex: 'code'
  },
  {
    title: '是否闲置',
    dataIndex: 'is_idle'
  },
  {
    title: '排',
    dataIndex: 'row_num'
  },
  {
    title: '列',
    dataIndex: 'column_num'
  },
  {
    title: '层',
    dataIndex: 'floor_num'
  },
  {
    title: '仓库名称',
    dataIndex: ['warehouse', 'name']
  },
  {
    title: '创建时间',
    dataIndex: 'create_time'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: appConfigStore.$state.compactFlag ? 120 : 140
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const currentWarehouse = ref({
  warehouse_id: '',
  warehouse_name: '',
  warehouse_code: undefined
})
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData, setQuery } = useQuery({
  fetchDataApi: async ({ limit, page, filter }) => {
    const res = await locationApi.queryList({ ...filter, limit, page })
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  fetchDeleteApi: async (id) => {
    const res = await locationApi.delete(id)
    return !!res
  },
  queryFormFilter: {
    warehouse_id: undefined,
    code: ''
  },
  queryFormOp: {}
})
eventEmitter.on(customEventName.QueryLocationList, (params) => {
  tableData.value = []
  currentWarehouse.value = params
  const warehouse_id = params.warehouse_id.toString()
  setQuery({ warehouse_id: warehouse_id?.split(',') }, true)
  onSearch()
})

// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize()

// ----------------------------主仓 添加/修改 ----------------------------

function addLocation() {
  eventEmitter.emit(customEventName.LocationFormModal, {
    title: '新增库位',
    data: {
      warehouse_id: unref(currentWarehouse).warehouse_id,
      warehouse_name: unref(currentWarehouse).warehouse_name,
      warehouse_code: unref(currentWarehouse).warehouse_code
    }
  })
}

function updateLocation(data) {
  eventEmitter.emit(customEventName.LocationFormModal, {
    title: '编辑库位',
    data: {
      warehouse_id: data.warehouse.id,
      warehouse_name: data.warehouse.name,
      warehouse_code: data.warehouse.code,
      ...data
    }
  })
}

// ---------------------------- 批量删除 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([])
const selectedRowList = ref([])

function onSelectChange(selectedRowKeys, selectedRows) {
  selectedRowKeyList.value = selectedRowKeys
  selectedRowList.value = selectedRows
}

// 批量删除
function confirmBatchDelete() {
  Modal.confirm({
    title: '提示',
    content: '确定要批量删除这些数据吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestBatchDelete()
    },
    cancelText: '取消',
    onCancel() {}
  })
}

//请求批量删除
async function requestBatchDelete() {
  try {
    await locationApi.delete(selectedRowKeyList.value.join(','))
    message.success('删除成功')
    selectedRowKeyList.value = []
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  }
}
// ------------------------------- 导出和导入 ---------------------------------
async function exportTemplate() {
  await locationApi.downloadTemplate({ warehouse_id: unref(currentWarehouse).warehouse_id })
}

const importModalRef = ref()
function showImportModal() {
  importModalRef.value.showImportModal()
}

// 导出
function onExport() {
  const data = {
    warehouse_id: unref(queryForm).warehouse_id,
    code: unref(queryForm).code
  }
  locationApi.exportXlsx(data)
}

// ----------------------------- 打印库位码 -----------------------------
const barcodeDetailRef = ref()
function printCode() {
  barcodeDetailRef.value.showDrawer(selectedRowList.value)
}
</script>
<style scoped lang="less">
.employee-fix {
  height: 85vh;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
</style>
